/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package br.com.fieo.sgee.logic;

import br.com.fieo.sgee.dao.DaoFactory;
import br.com.fieo.sgee.exception.ValidFieldException;
import br.com.fieo.sgee.model.Estimate;

/**
 * Classe para controlar as regras de négocio da entidade Estimate
 * @author rbueno
 */
public class EstimateLogic {

    /** Instancia da classe atual */
    private static EstimateLogic _instance = null;
    /** instancia da classe DaoFactory */
    private final DaoFactory factory;

    /**
     * obter uma intancia da classe
     * @return a intancia ativa
     */
    static public EstimateLogic getInstance() {
        if (_instance == null) {
            _instance = new EstimateLogic();
        }
        return _instance;
    }

    /**
     * Construtor privado para fazer com que a instancia do DaoFactory sejá unica
     */
    private EstimateLogic() {
        factory = new DaoFactory();
    }


    public Estimate loadLast(){
        return factory.getEstimateDao().loadLast();
    }

    /**
     * Muda o valor estimado naquele mês
     * @param estimate Estimativa preenchida
     * @throws EstimateException Caso algum campo tenha sido preenchido errado
     */
    public void merge(Estimate estimate) throws ValidFieldException {

        try {

            if (estimate.getValue() < 0) {
                throw new ValidFieldException(ValidFieldException.VALUE_INVALID_POSITIVE);
            }

            factory.beginTransaction();
            factory.getEstimateDao().merge(estimate);
            factory.commit();

        } catch (ValidFieldException e) {
            factory.rollback();
            throw e;
        }

    }
}
